package com.fare.taluo.application.impl.plane.city;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.fare.taluo.conf.system.DefaultPropertiesLoader;
import com.fare.taluo.vo.config.city.CitySelectVO;

/**
 * 城市选择框操作
 * @author xiangsf 2014-03-19
 *
 */
public class CitySelectOper {

	protected Logger logger = Logger.getLogger(getClass());
	public final static String ALL = "super";
	public final static String CITY = "CITY";
	public final static String PORT = "PORT";
	
	private List<Long> inlandList = new ArrayList<Long>();
	private List<Long> internationalList = new ArrayList<Long>();
	private List<Long> inlandHotlList = new ArrayList<Long>();
	private List<Long> internationaHotlList = new ArrayList<Long>();
	private Map<String, List<Long>> spellMaps = new HashMap<String , List<Long>>();
	
	private Map<String, Map<String,List<CitySelectVO>>> cityDatas;
	public CitySelectOper(Map<String, Map<String,List<CitySelectVO>>> cityDatas){
		this.cityDatas = cityDatas;
	}
	
	public void createJsFile(){
		try{
			for(String channel : cityDatas.keySet()){
				logger.info(String.format("build %s city select js file", channel));
				analyseCity(cityDatas.get(channel));
				analyseCity2(cityDatas.get(channel));
				buildFile(cityDatas.get(channel).get(PORT), String.format("%1$sfare%2$sjs%2$scity%2$scitylist%3$s.js", 
						DefaultPropertiesLoader.getRootPath(), File.separatorChar, channel));
				
				inlandList.clear();
				internationalList.clear();
				inlandHotlList.clear();
				internationaHotlList.clear();
				spellMaps.clear();
				
			}
			create_en_US_JsFile();
		}finally{
			this.destroy();
		}
	}
	
	public void create_en_US_JsFile(){
			for(String channel : cityDatas.keySet()){
				logger.info(String.format("build %s city select js file", channel));
				analyseCity(cityDatas.get(channel));
				analyseCity2(cityDatas.get(channel));
				buildFile_en_US_(cityDatas.get(channel).get(PORT), String.format("%1$sfare%2$sjs%2$scity%2$scitylist%3$s%4$s.js", 
						DefaultPropertiesLoader.getRootPath(), File.separatorChar, channel,"_en_US"));
				
				inlandList.clear();
				internationalList.clear();
				inlandHotlList.clear();
				internationaHotlList.clear();
				spellMaps.clear();
			}
	}
	

	private void analyseCity(Map<String, List<CitySelectVO>> channelMaps){
		List<CitySelectVO> ports = channelMaps.get(PORT);
		for (CitySelectVO vo : ports) {
			if(vo.isInternation() && !internationalList.contains(vo.getId())){
				internationalList.add(vo.getId());
				if(vo.isIshot())
					internationaHotlList.add(vo.getId());
			}else{
				inlandList.add(vo.getId());
				if(vo.isIshot())
					inlandHotlList.add(vo.getId());
			}
		}
	}
	
	private void analyseCity2(Map<String, List<CitySelectVO>> channelMaps){
		List<CitySelectVO> ports = channelMaps.get(PORT);
		String c = null;
		for (CitySelectVO vo : ports) {
			c = vo.getShortSpell()==null ? "" : vo.getShortSpell().toLowerCase().substring(0, 1);
			if("abcdef".indexOf(c)>=0){
				List<Long> cs = spellMaps.get("A-F");
				if(cs == null){ cs = new ArrayList<Long>();spellMaps.put("A-F", cs);}
				cs.add(vo.getId());
			}else if("ghij".indexOf(c)>=0){
				List<Long> cs = spellMaps.get("G-J");
				if(cs == null){ cs = new ArrayList<Long>();spellMaps.put("G-J", cs);}
				cs.add(vo.getId());
			}else if("klmn".indexOf(c)>=0){
				List<Long> cs = spellMaps.get("K-N");
				if(cs == null){ cs = new ArrayList<Long>();spellMaps.put("K-N", cs);}
				cs.add(vo.getId());
			}else if("opqrstuvw".indexOf(c)>=0){
				List<Long> cs = spellMaps.get("O-W");
				if(cs == null){ cs = new ArrayList<Long>();spellMaps.put("O-W", cs);}
				cs.add(vo.getId());
			}else if("xyz".indexOf(c)>=0){
				List<Long> cs = spellMaps.get("X-Z");
				if(cs == null){ cs = new ArrayList<Long>();spellMaps.put("X-Z", cs);}
				cs.add(vo.getId());
			}
		}
	}
	private void buildFile(List<CitySelectVO> citys,String path){
		StringBuffer buffer = new StringBuffer();
		File file = null;
		FileOutputStream out = null;
		try {
			buffer.append("//设置城市规则\n var labelFromcity =  new Array();\n");
			//国内热门
			if(inlandHotlList != null && !inlandHotlList.isEmpty()){
				buffer.append("labelFromcity['国内热门'] = new Array(" );
				if(inlandHotlList.size()==1) buffer.append("-1,"); //这里加一个冗余值，因为new Array(11)中11代表数组长度，而不是ID
				for (int i = 0; i < inlandHotlList.size(); i++) {
					buffer.append(inlandHotlList.get(i)+",");
				}
				buffer.deleteCharAt(buffer.lastIndexOf(","));
				buffer.append(");\n");
			}
			//国际热门
			if(internationaHotlList != null && !internationaHotlList.isEmpty()){
				buffer.append("labelFromcity['国际热门'] = new Array(" );
				if(internationaHotlList.size()==1) buffer.append("-1,"); //这里加一个冗余值，因为new Array(11)中11代表数组长度，而不是ID
				for (int i = 0; i < internationaHotlList.size(); i++) {
					buffer.append(internationaHotlList.get(i)+",");
				}
				buffer.deleteCharAt(buffer.lastIndexOf(","));
				buffer.append(");\n");
			}
//			//国内城市
//			if(inlandList != null && !inlandList.isEmpty()){
//				buffer.append("labelFromcity['国内城市'] = new Array(" );
//				for (int i = 0; i < inlandList.size(); i++) {
//					buffer.append(inlandList.get(i)+",");
//				}
//				buffer.deleteCharAt(buffer.lastIndexOf(","));
//				buffer.append(");\n");
//			}
//	        //国际城市
//			if(internationalList != null && !internationalList.isEmpty()){
//				buffer.append("labelFromcity['国际城市'] = new Array(" );
//				for (int i = 0; i < internationalList.size(); i++) {
//					buffer.append(internationalList.get(i)+",");
//				}
//				buffer.deleteCharAt(buffer.lastIndexOf(","));
//				buffer.append(");\n");
//			}
			//分['A-F'] ['G-J'] ['K-N'] ['P-W'] ['X-Z']
			List<String> keys = new ArrayList<String>(spellMaps.keySet());
			Collections.sort(keys);
			for(String key : keys){
				if(spellMaps.get(key) != null && !spellMaps.get(key).isEmpty()){
					buffer.append("labelFromcity['"+key+"'] = new Array(" );
					if(spellMaps.get(key).size()==1) buffer.append("-1,"); //这里加一个冗余值，因为new Array(11)中11代表数组长度，而不是ID
					for (int i = 0; i < spellMaps.get(key).size(); i++) {
						buffer.append(spellMaps.get(key).get(i)+",");
					}
					buffer.deleteCharAt(buffer.lastIndexOf(","));
					buffer.append(");\n");
				}
			}
			buffer.append("var citysFlight = new Array();\n");
			for(CitySelectVO c : citys){
				buffer.append("citysFlight[")
		    	.append(c.getId()).append("]=new Array('")
		    	.append(c.getCode()+"'")
		    	.append(",").append("'"+c.getName()+"'")
		    	.append(",").append("'"+c.getShortSpell()+"'")
		    	.append(",").append("'"+c.getFullSpell()+"'")
		    	.append(",").append("'"+c.getName()+"'")
		    	.append(");\n");
			}
			file = new File(path);
			
			if(file.exists()){
				//删除并重新创建
				file.delete();
				file.createNewFile();
			}
			out = new FileOutputStream(file);  
			out.write(buffer.toString().getBytes());
		} catch (Exception e) {
			e.printStackTrace();	
		}finally{
			if(out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			file = null;
			buffer = null;
		}	
	}
	
	/**
	 * 创建英文的JS
	 * @param citys
	 * @param path
	 */
	private void buildFile_en_US_(List<CitySelectVO> citys, String path) {
		StringBuffer buffer = new StringBuffer();
		File file = null;
		FileOutputStream out = null;
		try {
			buffer.append("//设置城市规则\n var labelFromcity =  new Array();\n");
			//国内热门
			if(inlandHotlList != null && !inlandHotlList.isEmpty()){
				buffer.append("labelFromcity['Domestic Hot '] = new Array(" );
				if(inlandHotlList.size()==1) buffer.append("-1,"); //这里加一个冗余值，因为new Array(11)中11代表数组长度，而不是ID
				for (int i = 0; i < inlandHotlList.size(); i++) {
					buffer.append(inlandHotlList.get(i)+",");
				}
				buffer.deleteCharAt(buffer.lastIndexOf(","));
				buffer.append(");\n");
			}
			//国际热门
			if(internationaHotlList != null && !internationaHotlList.isEmpty()){
				buffer.append("labelFromcity['International Hot'] = new Array(" );
				if(internationaHotlList.size()==1) buffer.append("-1,"); //这里加一个冗余值，因为new Array(11)中11代表数组长度，而不是ID
				for (int i = 0; i < internationaHotlList.size(); i++) {
					buffer.append(internationaHotlList.get(i)+",");
				}
				buffer.deleteCharAt(buffer.lastIndexOf(","));
				buffer.append(");\n");
			}
//			//国内城市
//			if(inlandList != null && !inlandList.isEmpty()){
//				buffer.append("labelFromcity['国内城市'] = new Array(" );
//				for (int i = 0; i < inlandList.size(); i++) {
//					buffer.append(inlandList.get(i)+",");
//				}
//				buffer.deleteCharAt(buffer.lastIndexOf(","));
//				buffer.append(");\n");
//			}
//	        //国际城市
//			if(internationalList != null && !internationalList.isEmpty()){
//				buffer.append("labelFromcity['国际城市'] = new Array(" );
//				for (int i = 0; i < internationalList.size(); i++) {
//					buffer.append(internationalList.get(i)+",");
//				}
//				buffer.deleteCharAt(buffer.lastIndexOf(","));
//				buffer.append(");\n");
//			}
			//分['A-F'] ['G-J'] ['K-N'] ['P-W'] ['X-Z']
			List<String> keys = new ArrayList<String>(spellMaps.keySet());
			Collections.sort(keys);
			for(String key : keys){
				if(spellMaps.get(key) != null && !spellMaps.get(key).isEmpty()){
					buffer.append("labelFromcity['"+key+"'] = new Array(" );
					if(spellMaps.get(key).size()==1) buffer.append("-1,"); //这里加一个冗余值，因为new Array(11)中11代表数组长度，而不是ID
					for (int i = 0; i < spellMaps.get(key).size(); i++) {
						buffer.append(spellMaps.get(key).get(i)+",");
					}
					buffer.deleteCharAt(buffer.lastIndexOf(","));
					buffer.append(");\n");
				}
			}
			buffer.append("var citysFlight = new Array();\n");
			for(CitySelectVO c : citys){
				if(null!=c.getFullSpell() && c.getFullSpell().indexOf(" ")>0){
					c.getFullSpell().replace(" ", "");
				}
				buffer.append("citysFlight[")
		    	.append(c.getId()).append("]=new Array('")
		    	.append(c.getCode()+"'")
		    	.append(",").append("'"+c.getFullSpell()+"("+c.getCode()+")'")
		    	.append(",").append("'"+c.getShortSpell()+"'")
		    	.append(",").append("'"+c.getFullSpell()+"'")
		    	.append(",").append("'"+c.getFullSpell()+"("+c.getCode()+")'")
		    	.append(");\n");
			}
			file = new File(path);
			
			if(file.exists()){
				//删除并重新创建
				file.delete();
				file.createNewFile();
			}
			out = new FileOutputStream(file);  
			out.write(buffer.toString().getBytes());
		} catch (Exception e) {
			e.printStackTrace();	
		}finally{
			if(out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			file = null;
			buffer = null;
		}	
		
	}
	
	private void destroy(){
		inlandList = null;
		internationalList = null;
		inlandHotlList = null;
		internationaHotlList = null;
		cityDatas = null;
		spellMaps = null;
	}
}
